package com.xindaoapp.happypet.activity;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.baidu.location.BaiDuLocationManager;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.bean.BaseEntity;
import com.xindaoapp.happypet.bean.NearFriends;
import com.xindaoapp.happypet.bean.NearFriends.Friend;
import com.xindaoapp.happypet.entry.Location;
import com.xindaoapp.happypet.fragments.UserInfoFragment;
import com.xindaoapp.happypet.ui.BaseActivity;
import com.xindaoapp.happypet.utils.BitmapUtil;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.ProgressHUD;
import com.xindaoapp.happypet.view.CircleImageView;

/**
 * 附近的宠友
 * 
 * @author
 * 
 */
public class ActivityNearFriend extends BaseActivity {
    private PullToRefreshListView listview;

    // public LocationClient mLocationClient = null;
    // public BDLocationListener myListener = new MyLocationListener();
    private BaiDuLocationManager locationManager;
    private Location location;

    // private double lat;
    // private double lon;
    // private String address;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        locationManager = BaiDuLocationManager.getInstance(ActivityNearFriend.this);
        locationManager.isLoadFirst = true;
        if (Constants.location_lat != 0 && Constants.location_lon != 0) {
            location = new Location(Constants.location_lat, Constants.location_lon, "");
        } else {
            locationManager.startLoacation(ActivityNearFriend.this, new IRequest<Location>() {
                @Override
                public void request(Location t) {
                    location = t;
                }
            });
        }
        getNearFriend(1);

        if (CommonUtil.isNetworkAvailable(this) != 0) {
            // InitLocation();
            locationManager.InitLocation();
        } else {
            Toast.makeText(getApplicationContext(), R.string.pLease_check_network,
                    Toast.LENGTH_SHORT).show();
            onDataArrived(false);
        }


    }

    @Override
    protected int getContentViewResId() {
        return R.layout.activity_nearfriend;
    }

    @Override
    protected void initViews() {
        listview = (PullToRefreshListView) findViewById(R.id.listview);
        listview.setMode(Mode.PULL_FROM_START);
        listview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                // InitLocation();
                locationManager.InitLocation();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                // 后台没做分页
            }
        });
    }

    private final NearFriendAdapter adapter = new NearFriendAdapter(this);

    private void getNearFriend(int page) {
        RequestParams params = new RequestParams();
        params.put("lat", String.valueOf(location.lat));
        params.put("lng", String.valueOf(location.lon));
        params.put("address", String.valueOf(location.address));
        AddClient.get(Address.NRERFRIEND, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                super.onSuccess(statusCode, content);
                listview.onRefreshComplete();
                try {
                    NearFriends parse = JSON.parseObject(content, NearFriends.class);
                    if (parse.getResult().equals("0")) {
                        adapter.addItems(parse.array);
                        listview.getRefreshableView().setAdapter(adapter);
                        onDataArrived(true);
                    } else {
                        onDataArrived(false);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    onDataArrived(false);
                }
            }

            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
                onDataArrived(false);
            }
        });
    }



    // private class MyLocationListener implements BDLocationListener {
    // @Override
    // public void onReceiveLocation(BDLocation location) {
    // lat = location.getLatitude();
    // lon = location.getLongitude();
    // address = location.getAddrStr();
    // getNearFriend(1);
    // }
    // }

    @Override
    protected void onStop() {
        // mLocationClient.stop();
        // mLocationClient.unRegisterLocationListener(myListener);
        locationManager.stopLocation();
        super.onStop();
    }

    public class NearFriendAdapter extends BaseAdapter {
        private final Context mContext;
        private List<Friend> arrays = new ArrayList<Friend>();

        public NearFriendAdapter(Context mContext) {
            super();
            this.mContext = mContext;
        }

        public void clearItems() {
            arrays.clear();
        }

        public void addItems(List<Friend> items) {
            arrays = items;
        }

        public List<Friend> getAll() {
            return arrays;
        }

        @Override
        public int getCount() {
            return arrays.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final Friend friend = arrays.get(position);
            final ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(mContext, R.layout.nearfriend_list_item, null);
                holder.pic = (CircleImageView) convertView.findViewById(R.id.pic);
                holder.name = (TextView) convertView.findViewById(R.id.name);
                holder.near = (TextView) convertView.findViewById(R.id.near);
                holder.pet = (TextView) convertView.findViewById(R.id.pet);
                holder.attention = (ImageView) convertView.findViewById(R.id.attention);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (CommonParameter.isLoadImg) {
                ImageLoader.getInstance().displayImage(friend.userface, holder.pic,
                        BitmapUtil.getPersonLoading());
            } else {
                holder.pic.setImageResource(R.drawable.person_loading);
            }
            holder.name.setText(friend.username);
            float distance = Float.valueOf(friend.distance);
            if (distance >= 1000) {
                distance = distance / 1000;
                holder.near.setText("距离" + formatDistance(distance) + "千米");
            } else {
                holder.near.setText("距离" + (int) distance + "米");
            }
            if (friend.isfollow.equals("0")) {
                holder.attention.setImageResource(R.drawable.other_guanzhu);
            } else if (friend.isfollow.equals("1")) {
                holder.attention.setImageResource(R.drawable.guanzhu_ok);
            }
            holder.attention.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (UserState.isLogged(ActivityNearFriend.this)) {
                        if (friend.isfollow.equals("0")) {
                            RequestParams params = new RequestParams();
                            params.put("follow_uid", friend.uid);
                            params.put("follow_username", friend.username);
                            final ProgressHUD ProgressDialog =
                                    ProgressHUD.show(mContext, "正在加载...", true, true, null);
                            AddClient.get(Address.GUANZHUOTHER, params,
                                    new AsyncHttpResponseHandler() {
                                        @Override
                                        public void onSuccess(int statusCode, String content) {
                                            if (null != ProgressDialog
                                                    && ProgressDialog.isShowing()) {
                                                ProgressDialog.dismiss();
                                            }
                                            try {
                                                BaseEntity parse =
                                                        JSON.parseObject(content, BaseEntity.class);
                                                if (parse.getResult().equals("0")) {
                                                    friend.isfollow = "1";
                                                    notifyDataSetChanged();
                                                    holder.attention
                                                            .setImageResource(R.drawable.guanzhu_ok);
                                                    Toast.makeText(mContext, "关注成功",
                                                            Toast.LENGTH_SHORT).show();
                                                } else {
                                                    Toast.makeText(mContext, "关注失败",
                                                            Toast.LENGTH_SHORT).show();
                                                }
                                            } catch (Exception e) {
                                                notifyDataSetChanged();
                                                Toast.makeText(mContext, "已关注", Toast.LENGTH_SHORT)
                                                        .show();
                                            }
                                            super.onSuccess(statusCode, content);
                                        }

                                        @Override
                                        public void onFailure(Throwable error, String content) {
                                            if (null != ProgressDialog
                                                    && ProgressDialog.isShowing()) {
                                                ProgressDialog.dismiss();
                                            }
                                            super.onFailure(error, content);
                                        }
                                    });
                        } else if (friend.isfollow.equals("1")) {
                            if (UserState.isLogged()) {
                                RequestParams params = new RequestParams();
                                params.put("follow_uid", friend.uid);
                                final ProgressHUD ProgressDialog =
                                        ProgressHUD.show(mContext, "正在加载...", true, true, null);
                                AddClient.get(Address.GUZNZHUDELETE, params,
                                        new AsyncHttpResponseHandler() {
                                            @Override
                                            public void onSuccess(int statusCode, String content) {
                                                if (null != ProgressDialog
                                                        && ProgressDialog.isShowing()) {
                                                    ProgressDialog.dismiss();
                                                }
                                                try {
                                                    friend.isfollow = "0";
                                                    notifyDataSetChanged();
                                                    holder.attention
                                                            .setImageResource(R.drawable.other_guanzhu);
                                                    Toast.makeText(mContext, "取消关注成功",
                                                            Toast.LENGTH_SHORT).show();
                                                    super.onSuccess(statusCode, content);
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            }

                                            @Override
                                            public void onFailure(Throwable error, String content) {
                                                if (null != ProgressDialog
                                                        && ProgressDialog.isShowing()) {
                                                    ProgressDialog.dismiss();
                                                }
                                                Toast.makeText(mContext, "关注失败", Toast.LENGTH_SHORT)
                                                        .show();
                                                super.onFailure(error, content);
                                            }
                                        });
                            }
                        }
                    }
                }
            });
            holder.pet.setText(friend.petbreed);
            convertView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Intent intent = new Intent(mContext, OtherActivity.class);
                    // intent.putExtra("uid", friend.uid);
                    // intent.putExtra("name", friend.username);
                    // intent.putExtra("face", friend.userface);
                    // startActivity(intent);

                    Intent intent = new Intent(mContext, MainActivity.class);
                    intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                            UserInfoFragment.class.getCanonicalName());
                    Bundle bundle = new Bundle();
                    bundle.putString(Constants.KEY_UID, friend.uid);
                    bundle.putString(Constants.KEY_USERNAME, friend.username);
                    bundle.putString(Constants.KEY_USERFACE, friend.userface);
                    intent.putExtra(Constants.KEY_BUNDLE, bundle);
                    mContext.startActivity(intent);

                }
            });

            return convertView;
        }

        class ViewHolder {
            CircleImageView pic;
            TextView name;
            TextView near;
            ImageView attention;
            TextView pet;
        }

        private String formatDistance(Float a) {
            DecimalFormat df = new DecimalFormat("0.0");
            return df.format(a);
        }
    }

    @Override
    protected OnClickListener getLeftViewClickListener() {
        return new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        };
    }

    @Override
    protected int getTopBarLeftImageViewRes() {
        return R.drawable.top_bar_back;
    }

    @Override
    protected String getTopBarTitleStrRes() {
        return "附近的宠友";
    }

}
